package com.haibara.aioj.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haibara.aioj.common.ErrorCode;
import com.haibara.aioj.constant.CommonConstant;
import com.haibara.aioj.exception.BusinessException;
import com.haibara.aioj.judge.service.JudgeService;
import com.haibara.aioj.mapper.QuestionSubmitMapper;
import com.haibara.aioj.model.dto.questionsubmit.JudgeInfo;
import com.haibara.aioj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.haibara.aioj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.haibara.aioj.model.entity.Question;
import com.haibara.aioj.model.entity.QuestionSubmit;
import com.haibara.aioj.model.entity.User;
import com.haibara.aioj.model.enums.QuestionSubmitLanguageEnum;
import com.haibara.aioj.model.enums.QuestionSubmitStatusEnum;
import com.haibara.aioj.model.vo.QuestionSubmitVO;
import com.haibara.aioj.model.vo.QuestionSubmitViewVO;
import com.haibara.aioj.rabbitmq.producer.MessageProducer;
import com.haibara.aioj.service.QuestionService;
import com.haibara.aioj.service.QuestionSubmitService;
import com.haibara.aioj.service.UserService;
import com.haibara.aioj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.haibara.aioj.constant.UserConstant.USER_LOGIN_STATE;
import static com.haibara.aioj.constant.RedisKey.*;

/**
* @author AiChan
* @description 针对表【question_sumbit(题目提交)】的数据库操作Service实现
* @createDate 2023-12-20 13:17:36
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MessageProducer messageProducer;

    /**
     * 提交题目
     *
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未知语言");
        }
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        question.setSubmitNum(question.getSubmitNum()+1);
        // 让对应的题目提交数+1
        questionService.updateById(question);
        long userId = loginUser.getId();
        // 锁必须要包裹住事务方法
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(userId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        // 设置题目状态为等待判题，存入数据库
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败");
        }

        Long questionSubmitId = questionSubmit.getId();
        // RabbitMQ 异步解耦，发送给代码沙箱进行判题
        messageProducer.sendMessage("aioj_exchange","aioj", String.valueOf(questionSubmitId));
        return questionSubmitId;
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        String sortField = questionSubmitQueryRequest.getSortField();
        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(language), "language", language);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVoPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVoPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVoPage.setRecords(questionSubmitVOList);
        return questionSubmitVoPage;
    }

    @Override
    public Page<QuestionSubmitViewVO> listQuestionSubmitByPage(String title, String language, long pageIndex, long size) {
        Page<QuestionSubmitViewVO> page = new Page<>(pageIndex, size);
        long total = 0;
        List<QuestionSubmitViewVO> records = new ArrayList<>();
        // Redis中储存了全部的题目提交信息，故只有当查询的title和language都为空时，才可以用Redis的信息
        if(StrUtil.isBlankIfStr(title)){
            long end = pageIndex +size-1;
            ZSetOperations<String, String> zSet = stringRedisTemplate.opsForZSet();
            // result
            Long temp = zSet.zCard(pageQuestionSubmitKey);
            if(temp != null) {
                // total 为题目提交信息总数
                total = temp;
            }
            // 从zSet中安装设定的顺序取出对应的题目提交id
            Set<String> strings = zSet.reverseRange(pageQuestionSubmitKey, pageIndex, end);
            ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
            if (strings != null) {
                // 通过题目提交id从redis中取出对应的题目提交信息
                for (String string : strings) {
                    String s = value.get(questionSubmitKey+string);
                    QuestionSubmitViewVO questionSubmitViewVO = JSONUtil.toBean(s,QuestionSubmitViewVO.class);
                    records.add(questionSubmitViewVO);
                }
            }
        }else {
            total = this.baseMapper.countQuestionSubmit(title, language);
            records = this.baseMapper.selectQuestionSubmit(title, language, pageIndex, size);
        }

        page.setTotal(total);
        if (size > 0) {
            page.setPages(total / size);
        }
        // 将JudgeInfo转换为Java对象并将其中的信息待返回前端的QuestionSubmit中
        records.forEach(recordItem -> {
            JudgeInfo judgeInfo = JSONUtil.toBean(recordItem.getJudgeInfo(), JudgeInfo.class);
            recordItem.setMemory(ObjectUtil.defaultIfNull(judgeInfo.getMemory(), 0) + "MB");
            recordItem.setMessage(judgeInfo.getMessage());
            recordItem.setTime(ObjectUtil.defaultIfNull(judgeInfo.getTime(), 0) + "ms");
        });
        page.setRecords(records);
        return page;
    }

    @Override
    public String getHistoryCode(Long questionId,HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        Long id = loginUser.getId();
        return this.baseMapper.getHistoryCode(questionId, id);
    }

    @Override
    public String getExampleCode(Long questionId) {
        Question byId = questionService.getById(questionId);
        return byId.getExampleCode();
    }
}




